package com.kunpan.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.kunpan.admin.annotation.AutoFill;
import com.kunpan.admin.async.MinioFileUploadAsyncService;
import com.kunpan.admin.common.Enum.BusinessType;
import com.kunpan.admin.common.domain.AjaxResult;
import com.kunpan.admin.common.redis.RedisMessagePublisher;
import com.kunpan.admin.common.utils.file.FileUtils;
import com.kunpan.admin.common.utils.file.MimeTypeUtils;
import com.kunpan.admin.entity.ChunkFile;
import com.kunpan.admin.entity.PanFile;
import com.kunpan.admin.entity.dto.MessageDto;
import com.kunpan.admin.entity.dto.PanFileDto;
import com.kunpan.admin.exception.file.InsufficientSpaceException;
import com.kunpan.admin.service.PanFileService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/pan/file")
public class PanFileController {

    @Autowired
    private PanFileService panFileService;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private RedisMessagePublisher redisMessagePublisher;
    private static final Logger logger = LoggerFactory.getLogger(PanFileController.class);


    /**
     * 查询当前用户的所有文件
     */
    @GetMapping("/list")
    public AjaxResult getFileList(PanFileDto panFileDto) {
        //开启分页查询
        PageHelper.startPage(panFileDto.getPageNum(), panFileDto.getPageSize());
        return panFileService.getFileList(panFileDto);
    }

    /**
     * 新建文件夹
     */
    @AutoFill(BusinessType.NEWFOLD)
    @PostMapping("/add")
    public AjaxResult addFolder(@RequestBody PanFile panFile) {
        return panFileService.addFolder(panFile);
    }

    /**
     * 判断能否秒传
     */
    @AutoFill(BusinessType.FASTUPLOAD)
    @PostMapping("/chuckMd5")
    public AjaxResult chuckFileMd5(@Param("fileSize") Long fileSize,
                                   @Param("parentId") Integer parentId,
                                   @Param("fileMd5") String fileMd5,
                                   @Param("fileName") String fileName) {
        try {
            // 文件上传逻辑
            return panFileService.chuckFileMd5Upload(fileSize, parentId, fileMd5, fileName);
        } catch (InsufficientSpaceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 小文件文件上传
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@Param("file") MultipartFile file,
                                 @Param("parentId") Integer parentId,
                                 @Param("fileMd5") String fileMd5) {
        try {
            // 文件上传逻辑
            return panFileService.fileUpload(file, parentId, fileMd5);
        } catch (InsufficientSpaceException e) {
            return AjaxResult.error(e.getMessage());
        }
//        return AjaxResult.success();
    }

    /**
     * 分片上传
     */
    @PostMapping("/chunk")
    public AjaxResult uploadFileChunk(MultipartFile file, ChunkFile chunkFile) {
        try {
            return panFileService.uploadFileChunk(file, chunkFile);
        } catch (InsufficientSpaceException e) {
            return AjaxResult.error(e.getMessage());
        }
//        if (Objects.equals(chunkFile.getTotalChunks(), chunkFile.getChunkNumber())) {
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            //通知前端文件分片合并成功
//            Map<String, String> messageMap = new HashMap<>();
//            messageMap.put("identifier", chunkFile.getIdentifier());
//            messageMap.put("status", "merged");
//            simpMessagingTemplate.convertAndSendToUser(StpUtil.getLoginId().toString(), "/progress", messageMap);
//        }
//        return AjaxResult.success();
    }

    /**
     * 合并分片请求
     */
    @PostMapping("/mergeFile")
    public AjaxResult mergeFile(@Param("fileMd5") String fileMd5,
                                @Param("parentId") Integer parentId,
                                @Param("shardTotal") Integer shardTotal,
                                @Param("fileSize") String fileName) {
        return panFileService.mergeChunkFile(fileMd5, parentId, shardTotal, fileName);
    }

    /**
     * 取消文件上传
     */
    @PostMapping("/cancelUpload")
    public AjaxResult cancelUpload(@Param("fileMd5") String fileMd5) {
        return panFileService.cancelFileUpload(fileMd5);
    }

    /**
     * 文件下载获取预签名URL
     */
    @GetMapping("/download")
    public AjaxResult fileDownload(@NotNull @Param("objectName") String objectName, @Param("fileSize") Long fileSize, HttpServletResponse response) {
        return panFileService.fileDownload(objectName, fileSize, response);
    }
}
